Nginx学习:使用nginx配置静态资源(js或者image)并访问后台的数据(使用vue中的ajax) 您所在的位置:网站首页 nginx 静态文件服务如何配置及优化服务内容 Nginx学习:使用nginx配置静态资源(js或者image)并访问后台的数据(使用vue中的ajax)

Nginx学习:使用nginx配置静态资源(js或者image)并访问后台的数据(使用vue中的ajax)

2023-07-30 05:10| 来源: 网络整理| 查看: 265

1.简介

由于今天学习了ngnix,并了解了其中的属性决定配置一个静态资源服务器,用于获取js以及访问后台的数据

2.当前nginx的配置conf #user nobody; worker_processes 1; error_log logs/error.log; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #开启gzip gzip on; server { listen 8000; server_name localhost; charset utf-8; #配置当前的图片 location ~ \.(gif|jpg|jpeg)$ { root static; } #配置当前所有以js和css结尾的数据都调用neginx的static文件夹中的内容 location ~ \.(js|css)$ { root static; } #将访问SpringBoot的请求转发到8080端口的SpringBoot location / { proxy_pass http://127.0.0.1:8080/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }

这就是我的配置:其中在当前的nginx中添加一个static文件夹,其中js中的内容为: 在这里插入图片描述 location / { proxy_pass http://127.0.0.1:8080/; },这句话表示当前所有的访问都会映射到当前的8080端口去

例如:访问localhost:8000/index就会访问到http://127.0.0.1:8080/index中去,注意这里的格式问题,proxy_pass中需要在最后面加上/

3.编写SpringBoot项目

当前的pom依赖

org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test junit junit test com.alibaba fastjson 1.2.58

项目结构: 在这里插入图片描述 当前的项目内容借鉴我的:vue之ajax访问后台(axios)

4.启动项目并开始访问

访问:http://localhost:8000/index的显示结果 在这里插入图片描述 发现当前的js全部都被nginx拦截并返回了! 在这里插入图片描述

执行vue的ajax访问后台 在这里插入图片描述 后台结果: 在这里插入图片描述

5.总结

1.使用nginx作为静态资源服务器的时候需要注意当前的路径匹配的问题,一旦路径不匹配就会出现404错误,还需要注意location的编写问题!

2.通过当前的nginx访问就会转发到指定的proxy_pass这个路径,前提是路径必须匹配,否者首页无法访问

3.通过nginx返回js的时候需要使用正则表达式来处理相对应的匹配问题!

以上纯属个人见解,如有问题请联系本人!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有